package com.flycms.web.system.rest;

import com.flycms.core.base.BaseController;
import com.flycms.core.entity.DataVo;
import com.flycms.core.entity.PageBean;
import com.flycms.core.entity.PageVo;
import com.flycms.core.entity.RestDataVo;
import com.flycms.module.admin.model.Admin;
import com.flycms.module.admin.model.Group;
import com.flycms.module.admin.model.Permission;
import com.flycms.module.admin.service.*;
import com.flycms.module.role.model.AdminRole;
import com.flycms.module.role.service.AdminRoleService;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 开发公司：宏石<br/>
 * 版权：宏石<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email xxx@qq.com
 * @Date: 2020-7-4
 */
@Controller
@RequestMapping("/rest/system/admin")
public class AdminRestController extends BaseController {

    @Autowired
    protected AdminRestService adminService;

    @Autowired
    protected GroupRestService groupService;

    @Autowired
    protected PermissionRestService permissionService;

    @Autowired
    protected AdminRoleService roleService;

    /**
     *  查询对应角色权限，或查询已有权限
     * @param groupId
     * @return RestDataVo
     */
    @GetMapping(value = {"/role_list/{groupId}","/role_list"})
    @ResponseBody
    public RestDataVo roleList(@PathVariable(value = "groupId",required = false) Long groupId){
        if(groupId!=null){
            return roleService.queryRoleByGroup(groupId);
        }
        return roleService.queryRoleList();
    }

    /**
     * 角色分配权限
     * @param groupId
     * @param roleId
     * @return
     */
    @PostMapping(value = "/role/insert/{groupId}/{roleId}")
    @ResponseBody
    public RestDataVo roleGroupAdd(@PathVariable(value = "groupId",required = false) Long groupId,
                              @PathVariable(value = "roleId",required = false) Long roleId){
        if(groupId!=null&&roleId!=null
                &&NumberUtils.isNumber(groupId+"")
                &&NumberUtils.isNumber(roleId+"")){
            return roleService.insertRoleGroup(roleId,groupId);
        }else{
            return RestDataVo.ERROR("参数错误");
        }
    }

    /**
     * 角色取消权限
     * @param groupId
     * @param roleId
     * @return
     */
    @PostMapping(value = "/role/delete/{groupId}/{roleId}")
    @ResponseBody
    public RestDataVo roleGroupDelete(@PathVariable(value = "groupId",required = false) Long groupId,
                              @PathVariable(value = "roleId",required = false) Long roleId){
        if(groupId!=null&&roleId!=null
                &&NumberUtils.isNumber(groupId+"")
                &&NumberUtils.isNumber(roleId+"")){
            return roleService.deleteRoleGroup(roleId,groupId);
        }else{
            return RestDataVo.ERROR("参数错误");
        }
    }

    /**
     * 新增权限
     * @param role
     * @return
     */
    @PostMapping(value = "/role/add")
    @ResponseBody
    public RestDataVo roleInsert(@RequestBody @Valid AdminRole role){
        return roleService.insertRole(role);
    }

    /**
     * 修改权限
     * @param role
     * @return
     */
    @PostMapping(value = {"/role/edit"})
    @ResponseBody
    public RestDataVo roleEdit(@RequestBody @Valid AdminRole role){
        return roleService.editRole(role);
    }

    /**
     * 修改权限为不可用
     * @param status
     * @param roleId
     * @return
     */
    @PostMapping(value = {"/role/edit/{roleId}/{status}"})
    @ResponseBody
    public RestDataVo roleEditStatus(@PathVariable(value = "status",required = false) String status,
                                     @PathVariable(value = "roleId",required = false) String roleId){
        if(status!=null&&roleId!=null
                &&NumberUtils.isNumber(status+"")
                &&NumberUtils.isNumber(roleId+"")){
            AdminRole role = roleService.queryRoleByPK(roleId);
            role.setStatus(Integer.parseInt(status));
            return roleService.editRole(role);
        }else{
            return RestDataVo.ERROR("参数错误");
        }
    }

    /**
     * 管理员用户列表
     * @param params
     * @return RestDataVo
     */
    @PostMapping(value = "/admin_list")
    @ResponseBody
    public RestDataVo adminList(@RequestBody Map<String,Object> params){
        String adminName=String.valueOf(params.get("adminName"));
        String nickName=String.valueOf(params.get("nickName"));
        String mobile=String.valueOf(params.get("mobile"));
        String email=String.valueOf(params.get("email"));
        int pageIndex=(int)params.get("pageIndex");
        int pageSize = (int)params.get("pageSize");
        PageVo<Admin> pageVo=adminService.getAdminListPage(adminName, nickName, mobile, email,pageIndex,pageSize);
        //List<Group> group = groupService.getAllGroupList();
        return RestDataVo.PAGE(pageVo.getList(),pageIndex,pageSize,pageVo.getCount());
    }


    /**
     * 处理和保存管理员信息
     * @param admin
     * @param result
     * @return RestDataVo
     */
    @PostMapping("/admin_save")
    @ResponseBody
    public RestDataVo addAdminSave(@RequestBody @Valid Admin admin, BindingResult result){
        RestDataVo data;
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            data = adminService.addAdmin(admin);
        } catch (Exception e) {
            return RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 处理和保存更新后管理员信息
     * @param admin
     * @param result
     * @return
     */
    @PostMapping("/admin_act")
    @ResponseBody
    public RestDataVo addAdminAct(@RequestBody @Valid Admin admin, BindingResult result){
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            return adminService.updateAdmin(admin);
        } catch (Exception e) {
            return RestDataVo.ERROR(e.getMessage());
        }
    }

    //删除管理员
    @PostMapping("/delAdmin/{id}")
    @ResponseBody
    public RestDataVo deleteAdminById(@PathVariable(value = "id") Long id){
        long group = (long) groupService.findUserAndGroupById(id);
        long adminGroup = 0L;
        List<Group> groupList = groupService.getAllGroupList();
        for (int i = 0; i < groupList.size(); i++) {
            if("超级管理员".equals(groupList.get(i))){
                adminGroup = groupList.get(i).getId();
            }
        }
        if(group == adminGroup){
            return RestDataVo.ERROR("超级管理员组不能删除");
        }
        return adminService.deleteAdminById(id);
    }


    /**
     * 我的密码修改
     * @param params
     * @return RestDataVo
     */
    @ResponseBody
    @PostMapping(value = "/password_update")
    public RestDataVo updatePassword(@RequestBody Map<String,Object> params) {
        RestDataVo data;
        String old_password=String.valueOf(params.get("old_password"));
        String password=String.valueOf(params.get("password"));
        String password_confirmation=String.valueOf(params.get("password_confirmation"));
        try {
            if (StringUtils.isBlank(old_password)) {
                return RestDataVo.ERROR("原来密码不能为空");
            } else if (old_password.length() < 6 && old_password.length() >= 32) {
                return RestDataVo.ERROR("密码最少6个字符，最多32个字符");
            }
            if (StringUtils.isBlank(password)) {
                return RestDataVo.ERROR("新密码不能为空");
            } else if (password.length() < 6 && password.length() >= 32) {
                return RestDataVo.ERROR("密码最少6个字符，最多32个字符");
            }
            if (!password.equals(password_confirmation)) {
                return RestDataVo.ERROR("两次密码必须一样");
            }
            data=adminService.updateAdminPassword(getAdminUser().getId(), old_password, password);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 权限列表
     * @param pageIndex
     * @param pageSize
     * @return RestDataVo
     */
    @GetMapping(value = "/permission_list/{pageIndex}/{pageSize}")
    @ResponseBody
    public RestDataVo permissionList(@PathVariable(value = "pageIndex") int pageIndex,
                                     @PathVariable(value = "pageSize") int pageSize){
        PageVo<Permission> pageVo=permissionService.getPermissionListPage(pageIndex,pageSize);
        return RestDataVo.PAGE(pageVo.getList(),pageIndex,pageSize,pageVo.getCount());
    }

    /**
     * 同步所有权限
     * @return
     */
    @GetMapping("/permission_sync")
    @ResponseBody
    public RestDataVo getSyncAllPermission(){
        if(permissionService.getSyncAllPermission()){
            return RestDataVo.OK("同步权限成功");
        }
        return RestDataVo.ERROR("同步权限失败");
    }

    //删除权限节点
    @PostMapping("/permission_del")
    @ResponseBody
    public RestDataVo deletePermission(@RequestParam(value = "id") Long id){
        RestDataVo data;
        if(permissionService.deletePermission(id)){
            data = RestDataVo.OK("该权限已删除");
        }else{
            data = RestDataVo.ERROR("删除失败或者不存在！");
        }
        return data;
    }

    @GetMapping(value = "/permission_update/{id}")
    public String updatePermissions(@PathVariable Long id, ModelMap modelMap){
        Permission permission = permissionService.findPermissionById(id);
        if(permission==null){
            modelMap.addAttribute("message", "该权限不存在");
            return theme.getAdminTemplate("common/message_tip");
        }
        modelMap.put("permission", permission);
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("admin/admin_permission_update");
    }

    //处理用户组信息
    @PostMapping("/permission_update_save")
    @ResponseBody
    public RestDataVo updatePermissionsSave(@RequestBody @Valid Permission permission, BindingResult result){
        RestDataVo data;
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            data = permissionService.updatePermissions(permission);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    //添加用户权限
    @GetMapping(value = "/add_group")
    public String getAddGroup(ModelMap modelMap){
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("admin/group_add");
    }

    //处理用户组信息
    @PostMapping("/add_group_save")
    @ResponseBody
    public DataVo getAddGroupSave(@RequestParam(value = "name", required = false) String name){
        if (StringUtils.isBlank(name)) {
            return DataVo.failure("会员组名不能为空");
        }
        return groupService.addGroup(name);
    }

    //删除权限组
    @PostMapping("/group_del")
    @ResponseBody
    public DataVo deleteGroup(@RequestParam(value = "id") Long id){
        DataVo data = DataVo.failure("操作失败");
        if(id==1){
            return data = DataVo.failure("超级管理员组不能删除");
        }
        if(groupService.deleteGroup(id)){
            data = DataVo.success("该权限组已删除");
        }else{
            data = DataVo.failure("删除失败或者不存在！");
        }
        return data;
    }

    @GetMapping(value = "/group_update/{id}")
    public String updateGroup(@PathVariable Long id, ModelMap modelMap){
        Group group = groupService.findGroupById(id);
        if(group==null){
            modelMap.addAttribute("message", "该管理组不存在");
            return theme.getAdminTemplate("common/message_tip");
        }
        modelMap.put("group", group);
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("admin/group_update");
    }

    //处理用户组信息
    @PostMapping("/update_group_save")
    @ResponseBody
    public DataVo updateGroup(@RequestParam(value = "id", required = false) String id,@RequestParam(value = "name", required = false) String name){
        if (StringUtils.isBlank(name)) {
            return DataVo.failure("会员组名不能为空");
        }
        if (!NumberUtils.isNumber(id)) {
            return DataVo.failure("参数传递错误");
        }
        return groupService.updateGroup(name,Long.parseLong(id));
    }

    @GetMapping(value = "/group_list")
    public String roleList(@RequestParam(value = "p", defaultValue = "1") int pageNum,ModelMap modelMap){
        PageVo<Group> pageVo=groupService.getGroupListPage(pageNum,20);
        modelMap.put("pageVo", pageVo);
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("admin/group_list");
    }


    @GetMapping(value = "/group_assignPermissions/{id}")
    public String assignPermissions(@PathVariable Long id, ModelMap modelMap){
        Group group = groupService.findGroupById(id);
        if(group==null){
            modelMap.addAttribute("message", "该管理组不存在");
            return theme.getAdminTemplate("common/message_tip");
        }
        List<Permission> permissionList = permissionService.getAllPermissions();
        LinkedHashMap<String, List<Permission>> permissionMap = permissionService.groupByController(permissionList);
        modelMap.put("group", group);
        modelMap.put("permissionMap", permissionMap);
        modelMap.addAttribute("admin", getAdminUser());
        return theme.getAdminTemplate("admin/group_assign_permissions");
    }

    @ResponseBody
    @PostMapping(value = "/group_markpermissions")
    public DataVo addGroup(@RequestParam(value = "groupId", defaultValue = "0") Long groupId,@RequestParam(value = "permissionId", defaultValue = "0") Long permissionId) {
        DataVo data = DataVo.failure("操作失败");
        if(groupId==1){
            return data = DataVo.failure("超级管理员组权限不能修改");
        }
        if(groupId==0 || permissionId==0){
            return data.failure("参数错误！");
        }
        if(permissionService.markAssignedPermissions(groupId,permissionId)){
            if(groupService.deleteGroupPermission(groupId,permissionId)){
                return data.success("删除成功！");
            }else{
                return data.failure("删除失败！");
            }
        }else{
            if(groupService.addGroupPermission(groupId,permissionId)){
                return DataVo.success("添加成功！");
            }else{
                return DataVo.failure("添加失败！");
            }
        }
    }
}
